package config;

import cn.zcy.condition.LinuxCondition;
import cn.zcy.condition.WindowsCondition;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

public class JdbcConfig {

    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.driver}")
    private String driver;

    /**
     * 创建数据源，使用spring内置数据源
     *
     * @return
     */
    @Bean("dataSource")
    @Conditional(WindowsCondition.class)
    public DataSource createWindowsDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        System.out.println("windowsUsername = " + username);
        return dataSource;
    }

    @Conditional(LinuxCondition.class)
    @Bean("dataSource")
    public DataSource createLinuxDataSource(@Value("${jdbc.linuxusername}") String linuxUsername,
                                            @Value("${jdbc.linuxpassword}") String linuxPassword,
                                            @Value("${jdbc.linuxdriver}") String linuxDriver,
                                            @Value("${jdbc.linuxurl}") String linuxUrl) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(linuxDriver);
        dataSource.setUrl(linuxUrl);
        dataSource.setUsername(linuxUsername);
        dataSource.setPassword(linuxPassword);
        System.out.println("linuxUsername = " + linuxUsername);
        return dataSource;
    }
}
